//
//  KSComPicker.swift
//  Slaughter
//
//  Created by 邱仙凯 on 2022/1/12.
//  Copyright © 2025 aowang. All rights reserved.
//  多级滚动选择器

import UIKit

class KSComPicker:UIView {
   private var contentV:UIView!
   private var bg:UIView!
   
    private  var picker = UIPickerView()
    
    
    private  lazy var cancleBtn:UIButton = {
        let v = UIButton()
        v.setTitle("取消", for: .normal)
        v.setTitleColor(.lightGray, for: .normal)
        return v
    }()
    private  lazy var centerLab:UILabel = {
        let v = UILabel()
        v.textAlignment = .center
        v.text = "请选择"
        v.textColor = .darkGray
        v.font = UIFont.systemFont(ofSize: 19)
        return v
    }()
    private  lazy var chooseBtn:UIButton = {
        let v = UIButton()
        v.setTitle("选择", for: .normal)
        v.setTitleColor(Theme.primaryColor(), for: .normal)
        return v
    }()
    private  lazy var confirmBtn:UIButton = {
        let v = UIButton()
        v.setTitle("确定", for: .normal)
        v.setTitleColor(Theme.primaryColor(), for: .normal)
        return v
    }()
    private  lazy var searchBar:UISearchBar = {
        let v = UISearchBar()
          v.placeholder = "搜索"
        v.backgroundImage = UIImage()
        v.delegate = self
         return v
    }()
 
  
    
    
    private let contH:CGFloat = 420
    var numberOfComponents = 0
    var numberOfRowsInComponentClo:((Int)->(Int))?
    var titleForRowClo:((Int,Int)->(String))?
    var resultClosure:(()->())?
     var didSelectRowClo:((Int,Int)->())?
    var searchClo:((String)->())?
    var multiSelect = false
    func getNumberOfComponents() -> Int {
        return picker.numberOfComponents
    }
    init(frame: CGRect,multiSelect:Bool = false){
        super.init(frame: frame)
        self.multiSelect = multiSelect
        setup()
    }
    func setup() {
        self.isUserInteractionEnabled = true
        let gr = UITapGestureRecognizer(target: self, action: #selector(close))
        gr.numberOfTapsRequired = 1
        bg = UIView(frame: CGRect(x:0,y: 0 ,width: KSGlobal.screenW,height: KSGlobal.screenH))
        bg.isUserInteractionEnabled = true
        bg.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        addSubview(bg)
        bg.addGestureRecognizer(gr)
        
        
        contentV = UIView(frame: CGRect(x:0,y:KSGlobal.screenH,width: KSGlobal.screenW,height: contH))
        contentV.setMutiBorderRoundingCorners(corner: [.topLeft,.topRight], number: 12)
        contentV.backgroundColor = .white
        addSubview(contentV)
        
        picker.frame = CGRect(x:0,y:80,width: contentV.ks_width,height: contH - 80)
       
        picker.delegate = self
        picker.dataSource = self
        contentV.addSubview(picker)
        
        cancleBtn.frame = CGRect(x: 3, y: 3, width: 60, height: 35)
        contentV.addSubview(cancleBtn)
        cancleBtn.addTarget(self, action: #selector(close), for: .touchUpInside)
        
        centerLab.frame = CGRect(x: contentV.ks_width/2 - 30, y: 3, width: 60, height: 35)
        contentV.addSubview(centerLab)
        
        confirmBtn.frame = CGRect(x: contentV.ks_width - 63, y: 3, width: 60, height: 35)
        contentV.addSubview(confirmBtn)
        confirmBtn.addTarget(self, action: #selector(confirm), for: .touchUpInside)
        
        if multiSelect {
            chooseBtn.frame = CGRect(x: contentV.ks_width - 123, y: 3, width: 60, height: 35)
            contentV.addSubview(chooseBtn)
            chooseBtn.addTarget(self, action: #selector(choose), for: .touchUpInside)
        }
        
        
        searchBar.frame = CGRect(x: 10, y: 50, width: KSGlobal.screenW - 20, height: 35)
        contentV.addSubview(searchBar)
        
        picker.reloadAllComponents()
         
    }
    func reloadAllComp() {
        picker.reloadAllComponents()
    }
    func selectA(comp:Int,row:Int) {
        picker.reloadComponent(comp)
         picker.selectRow(row, inComponent: comp, animated: true)
    }
    func reloadComp(comp:Int) {
        picker.reloadComponent(comp)
    }
    @objc func choose(){
       
    }
    
    @objc func confirm(){
        if let clo = self.resultClosure {
            clo()
        }
        self.close()
    }
    
    
    override func willMove(toSuperview newSuperview: UIView?) {
        
        if newSuperview.isSome {
            UIView.animate(withDuration: 0.2) { //  出现时
                self.contentV.ks_y = KSGlobal.screenH - self.contH
            }
        }
        
    }
    
    @objc func close(){
        UIView.animate(withDuration: 0.2) {
            self.contentV.ks_y = KSGlobal.screenH
        }
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
            self.removeFromSuperview()
        }
        
        
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
extension KSComPicker:UISearchBarDelegate {
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        if let clo = searchClo {
            clo(searchBar.text.unwrap)
        }
    }
}

extension KSComPicker: UIPickerViewDelegate, UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
           return numberOfComponents
     }
     func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
         if let clo = numberOfRowsInComponentClo {
             return clo(component)
         } else {
             return 0
         }
     }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        
        
        var label = view as? UILabel
            if label == nil {
                label = UILabel.init()
                label?.font = UIFont.systemFont(ofSize: 20)
                label?.textColor = UIColor.black
                label?.textAlignment = .center
                label?.minimumScaleFactor = 0.5
                label?.adjustsFontSizeToFitWidth = true
                label?.numberOfLines = 2
            }
        
//        let label :UILabel = UILabel()
//        label.textAlignment = .center
//        label.font = UIFont.systemFont(ofSize: 20)
//        label.textColor = UIColor.black
        if let clo = self.titleForRowClo {
            let result = clo(component,row)
            label!.text = result
        }
         return label!
    }
    
    func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        let attrStr = NSMutableAttributedString()
        attrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: NSRange(location: 0, length: 1))
        return attrStr
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
      
        if let clo = self.didSelectRowClo {
            clo(component,row)
        }
    }
}
